<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="120px">
      <el-input v-model="form.id" v-show="false" v-bind:disabled="true"></el-input>
      <el-form-item label="等级名">
        <el-input v-model="form.name" ></el-input>
      </el-form-item>
      <el-form-item label="权限">
        <el-checkbox-group v-model="form.permissions">
          <template v-for="permission in permissions">
            <el-checkbox :label="permission.name" name="permissions"></el-checkbox>
          </template>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button @click="onCancel">Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { getRole, editRole } from '@/api/role'
  import { getPermissionListAll } from '@/api/permission'

  export default {
    data() {
      return {
        form: {
          id: 0,
          name: '',
          permissions: []
        },
        permissions: {}
      }
    },
    created() {
      getPermissionListAll().then(response => {
        this.permissions = response.data.content
        this.form.id = this.$route.query.id
        getRole(this.form.id).then(response => {
          this.form.name = response.data.name
          for (var per in response.data.permissions) {
            this.form.permissions[this.form.permissions.length] = response.data.permissions[per].name
          }
        })
      })
    },
    methods: {
      onSubmit() {
        editRole(this.form.id, this.form.name, this.form.permissions).then(response => {
          if (response.code === 1) {
            this.$message('修改成功!')
            this.$router.push({ path: '/sys/role' })
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
      },
      onCancel() {
        this.$router.push({ path: '/sys/role' })
      }
    }
  }
</script>

<style scoped>
  .line {
    text-align: center;
  }
</style>

